from flask import Blueprint, request, jsonify, send_file
from models import db, ResumeAttachment, ContractAttachment, CertificateAttachment, Employee
import os
import mimetypes

attachment_bp = Blueprint('attachment', __name__)

# 简历附件
@attachment_bp.route('/api/employees/<int:employee_id>/attachments', methods=['GET'])
def get_resume_attachments(employee_id):
    attachments = ResumeAttachment.query.filter_by(employee_id=employee_id).all()
    return jsonify([att.to_dict() for att in attachments])

@attachment_bp.route('/api/employees/<int:employee_id>/attachments', methods=['POST'])
def create_resume_attachment(employee_id):
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    
    # 检查员工是否存在
    employee = Employee.query.get_or_404(employee_id)
    
    # 获取附件描述
    description = request.form.get('description', '')
    uploader = request.form.get('uploader', '系统')
    
    # 获取文件类型
    filetype = file.content_type or mimetypes.guess_type(file.filename)[0] or 'application/octet-stream'
    
    # 创建附件记录
    attachment = ResumeAttachment(
        employee_id=employee_id,
        filename=file.filename,
        filesize=0,  # 暂时设置为0，稍后更新
        filetype=filetype,
        description=description,
        filepath='',  # 暂时为空，稍后更新
        uploader=uploader
    )
    
    # 先添加记录获取ID
    db.session.add(attachment)
    db.session.flush()
    
    # 使用获取的ID生成文件路径
    filepath = ResumeAttachment.get_path(attachment, file.filename)
    attachment.filepath = filepath
    
    # 确保上传目录存在
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    
    # 保存文件
    file.save(filepath)
    
    # 更新文件大小
    attachment.filesize = os.path.getsize(filepath)
    
    # 提交更改
    db.session.commit()
    
    return jsonify(attachment.to_dict()), 201

@attachment_bp.route('/api/employees/<int:employee_id>/attachments/<int:id>', methods=['DELETE'])
def delete_resume_attachment(employee_id, id):
    att = ResumeAttachment.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    db.session.delete(att)
    db.session.commit()
    return jsonify({'message': '删除成功'})

# 合同附件
@attachment_bp.route('/api/contracts/<int:contract_id>/attachments', methods=['GET'])
def get_contract_attachments(contract_id):
    attachments = ContractAttachment.query.filter_by(contract_id=contract_id).all()
    return jsonify([att.to_dict() for att in attachments])

# 注释掉POST路由，避免与主app.py冲突
# @attachment_bp.route('/api/contracts/<int:contract_id>/attachments', methods=['POST'])
# def create_contract_attachment(contract_id):
#     data = request.get_json()
#     data['contract_id'] = contract_id
#     att = ContractAttachment(**data)
#     db.session.add(att)
#     db.session.commit()
#     return jsonify({'message': '创建成功', 'id': att.id}), 201

@attachment_bp.route('/api/contracts/<int:contract_id>/attachments/<int:id>', methods=['DELETE'])
def delete_contract_attachment(contract_id, id):
    att = ContractAttachment.query.filter_by(id=id, contract_id=contract_id).first_or_404()
    db.session.delete(att)
    db.session.commit()
    return jsonify({'message': '删除成功'})

# 证书附件
@attachment_bp.route('/api/certificates/<int:certificate_id>/attachments', methods=['GET'])
def get_certificate_attachments(certificate_id):
    attachments = CertificateAttachment.query.filter_by(certificate_id=certificate_id).all()
    return jsonify([att.to_dict() for att in attachments])

@attachment_bp.route('/api/certificates/<int:certificate_id>/attachments', methods=['POST'])
def create_certificate_attachment(certificate_id):
    # 处理 multipart/form-data 文件上传
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    description = request.form.get('description', '')
    uploader = request.form.get('uploader', '系统')
    # 保存文件
    filename = file.filename
    filepath = CertificateAttachment.get_path(filename=filename)
    file.save(filepath)
    # 创建附件记录
    att = CertificateAttachment(
        certificate_id=certificate_id,
        filename=filename,
        filesize=os.path.getsize(filepath),
        filetype=file.content_type,
        description=description,
        filepath=filepath,
        uploader=uploader
    )
    db.session.add(att)
    db.session.commit()
    return jsonify({'message': '创建成功', 'id': att.id}), 201

@attachment_bp.route('/api/certificates/<int:certificate_id>/attachments/<int:attachment_id>', methods=['DELETE'])
def delete_certificate_attachment(certificate_id, attachment_id):
    att = CertificateAttachment.query.filter_by(id=attachment_id, certificate_id=certificate_id).first_or_404()
    db.session.delete(att)
    db.session.commit()
    return jsonify({'message': '删除成功'})

# 简历附件下载接口
@attachment_bp.route('/api/employees/<int:employee_id>/attachments/download/<int:attachment_id>', methods=['GET'])
def download_resume_attachment(employee_id, attachment_id):
    att = ResumeAttachment.query.filter_by(id=attachment_id, employee_id=employee_id).first_or_404()
    if not os.path.exists(att.filepath):
        return jsonify({'error': 'File not found'}), 404
    return send_file(
        att.filepath,
        mimetype=att.filetype or 'application/octet-stream',
        as_attachment=True,
        download_name=att.filename
    ) 